package com.youlai.system.common.util;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 陈子杰
 * @Description 对象复制工具类
 * @Version 1.0.0
 * @Date 2022/11/19 2:48
 */
public class BeanCopyUtils {
    /**
     * 对象复制
     *
     * @param source 源对象
     * @param target 目标对象
     * @param <T>
     * @return
     */
    public static <T> T copyObject(Object source, Class<T> target) {
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * List集合复制
     *
     * @param sourceList 源集合
     * @param target     目标集合
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList(List<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyObject(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * set集合复制
     *
     * @param sourceList 源集合
     * @param target     目标集合
     * @param <T>
     * @return
     */
    public static <T> Set<T> copySet(Set<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyObject(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
